<template>
  <div class="app-container oneSearchNoFooter">
    <div class="customContainer">
      <!-- 搜索头 -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <el-form-item>
          <el-select
            placeholder="选择品牌"
            v-model="formInline.brand_id"
            filterable
            @change="brandChange"
          >
            <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select placeholder="选择关联状态" v-model="formInline.is_related" filterable>
            <el-option v-for="item in type_list" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="formInline.name"
            placeholder="请输入代金券名称"
            @keyup.enter.native="searchClick"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <dj-button size="small" @search="searchClick">
            <template #default>搜索</template>
          </dj-button>
        </el-form-item>
        <el-button class="pull-right" type="primary" size="small" @click="addEditClick()">新增代金券</el-button>
      </el-form>
      <!-- 表格 -->
      <el-table highlight-current-row :data="list" v-loading.body="listLoading" border size="small">
        <el-table-column align="center" label="代金券名称">
          <template slot-scope="scope">
            <el-button type="text" @click="addEditClick(scope.row)">{{scope.row.name}}</el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="代金券详情">
          <template slot-scope="scope">
            {{scope.row.limit_money}}元抵{{scope.row.discount_money}}元（满{{scope.row.threshold}}元可用）
            <span
              v-if="scope.row.number>0"
            >单笔限定使用{{scope.row.number}}张</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="生效时间">
          <template slot-scope="scope">{{scope.row.effect_time+' - '+scope.row.stop_time}}</template>
        </el-table-column>
        <el-table-column align="center" label="备注" prop="remark"></el-table-column>
        <el-table-column align="center" label="操作" width="240px">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.is_enable == 1"
              type="success"
              size="mini"
              @click="stateClick(scope.row.id,scope.$index,0)"
            >已启用</el-button>
            <el-button v-else size="mini" @click="stateClick(scope.row.id,scope.$index,1)">已停用</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delPackageClick(scope.row.id,scope.$index)"
            ></el-button>
            <el-button type="primary" plain size="mini" @click="deployStoreClick(scope.row.id)">配置门店</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 新增编辑弹框 -->
      <el-dialog
        style="margin-top:-8vh"
        :close-on-click-modal="false"
        width="580px"
        :title="is_edit? '代金券详情':'新增代金券'"
        :visible.sync="addEditDialog"
        @close="callOf('saveForm')"
      >
        <el-form
          v-if="addEditDialog"
          :model="saveForm"
          size="small"
          ref="saveForm"
          :rules="rules"
          :inline="true"
          :key="formInline.is_related"
        >
          <!-- <el-form-item label="关联第三方卡券" v-if="is_edit && saveForm.is_related==1">
                        <el-popover placement="top-start" title="卡券详情" width="400" trigger="click">
                            <p>卡券名称：{{product_info.name}}</p>
                            <p>卡券金额：{{product_info.money}}</p>
                            <p>&#x3000;卡券码：{{product_info.id}}</p>
                            <p>使用规则：{{product_info.use_rules}}</p>
                            <p>&#x3000;有效期：{{product_info.effect_time}} - {{product_info.stop_time}}</p>
                            <p class="text_overflow">适用门店：<span v-for="(item,index) in product_info.store_list"
                                    :key="index">{{item}}、</span></p>
                            <p>卡券说明：{{product_info.remark}}</p>
                            <el-button slot="reference" type="text" @click="getProduct(saveForm.product_id)">商品ID：
                                {{saveForm.product_id}}</el-button>
                        </el-popover>
          </el-form-item>-->
          <el-form-item style="display: inline-block">
            <el-checkbox
              :disabled="is_edit"
              v-model="saveForm.is_re"
              @change="relatedChange"
            >关联第三方商品</el-checkbox>
          </el-form-item>
          <el-form-item
            v-if="saveForm.is_re"
            prop="is_collect"
            style="width:125px; display: inline-block"
          >
            <el-select :disabled="is_edit" size="mini" filterable v-model="saveForm.is_collect">
              <el-option
                v-for="item in related_list"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="saveForm.is_re&&saveForm.is_collect*1<3"
            prop="product_id"
            style="width:125px; display: inline-block"
          >
            <el-input
              :disabled="is_edit"
              size="mini"
              placeholder="输入商品ID"
              v-model="saveForm.product_id"
            ></el-input>
          </el-form-item>
          <el-form-item label="　　　券名称" required prop="name">
            <el-input
              :disabled="is_edit"
              :maxlength="20"
              placeholder="请输入券名称(二十字内)"
              v-model="saveForm.name"
              style="width:390px;"
            ></el-input>
          </el-form-item>
          <el-form-item label="　　　券售价" required prop="limit_money">
            <el-input
              :disabled="is_edit"
              type="number"
              style="width:135px;"
              placeholder="输入金额"
              onmousewheel="return false;"
              min="0"
              v-model="saveForm.limit_money"
            ></el-input>
          </el-form-item>
          <el-form-item label="　可抵扣金额" required prop="discount_money">
            <el-input
              :disabled="is_edit"
              type="number"
              style="width:135px;"
              onmousewheel="return false;"
              min="0"
              v-model="saveForm.discount_money"
              placeholder="输入金额"
            ></el-input>
          </el-form-item>
          <el-form-item label="　　使用门槛" required prop="threshold">
            <el-input
              :disabled="is_edit"
              type="number"
              style="width:135px;"
              onmousewheel="return false;"
              min="0"
              v-model="saveForm.threshold"
              placeholder="输入金额"
            ></el-input>
            <span class="indexColor">消费满X元后券可用</span>
          </el-form-item>
          <el-form-item label="　　生效日期" required prop="pickerDate">
            <el-date-picker
              style="width:390px;"
              :disabled="is_edit"
              :editable="false"
              :clearable="false"
              v-model="saveForm.pickerDate"
              value-format="yyyy-MM-dd"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="　　适用业务" required>
            <div>
              <el-checkbox
                :disabled="is_edit"
                label="充值办卡"
                name="type"
                v-model="saveForm.is_recharge"
                @change="applyChange(1)"
              ></el-checkbox>
              <el-select
                style="width:300px"
                :disabled="!saveForm.is_recharge||is_edit"
                multiple
                v-model="saveForm.recharge_id"
              >
                <el-option
                  v-for="item in recharge_list"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
              <div style="width:300px;line-height: 20px" class="indexColor">
                支持办理或升级成选定的卡类型
                <br />支持对选定的卡类型进行普通充值和充值续期
              </div>
            </div>
            <div>
              <el-checkbox
                :disabled="is_edit"
                label="缴费续期"
                name="type"
                v-model="saveForm.is_pay_renewal"
                @change="applyChange(2)"
              ></el-checkbox>
              <el-select
                style="width:300px"
                :disabled="!saveForm.is_pay_renewal||is_edit"
                multiple
                v-model="saveForm.pay_renewal_id"
              >
                <el-option
                  v-for="item in pay_renewal_list"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
              <div style="width:300px;line-height: 20px" class="indexColor">支持选定卡类型的缴费续期</div>
            </div>
            <div>
              <el-checkbox
                :disabled="is_edit"
                label="缴费办卡"
                name="type"
                v-model="saveForm.is_pay_card"
                @change="applyChange(3)"
              ></el-checkbox>
              <el-select
                style="width:300px"
                :disabled="!saveForm.is_pay_card||is_edit"
                multiple
                v-model="saveForm.pay_card_id"
              >
                <el-option
                  v-for="item in pay_card_list"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
              <div style="width:300px;line-height: 20px" class="indexColor">支持选定卡类型的缴费办卡</div>
            </div>
            <div>
              <el-checkbox
                :disabled="is_edit"
                true-label="1"
                false-label="0"
                label="门票类套餐"
                name="type"
                v-model="saveForm.is_ticket"
              ></el-checkbox>
              <div style="width:300px;line-height: 20px" class="indexColor">
                支持无卡套餐的办理以及刷卡套餐的陪同票办理
                <br />(补办陪同票不适用)
              </div>
            </div>
          </el-form-item>
          <el-form-item label="限定使用张数" required prop="number">
            <el-input
              :disabled="is_edit"
              onkeypress="return event.which>=48&&event.which<=57"
              type="number"
              style="width:125px;"
              onmousewheel="return false;"
              min="0"
              v-model="saveForm.number"
              placeholder="输入张数"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <div style="width:210px;line-height: 15px" class="indexColor">限定该代金券在单笔消费中的使用张数上限</div>
          </el-form-item>
          <el-form-item label="· 　　备注　　">
            <el-input
              :disabled="is_edit"
              style="width:390px"
              type="textarea"
              v-model="saveForm.remark"
              :maxlength="150"
              placeholder="输入备注150字内"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button
            v-if="!is_edit"
            type="primary"
            @click="savePackageClick('saveForm')"
            size="small"
          >确 定</el-button>
        </div>
      </el-dialog>
      <!-- 配置门店弹框 -->
      <el-dialog
        :close-on-click-modal="false"
        width="650px"
        title="选择门店"
        :visible.sync="storeDialog"
      >
        <div>
          <div class="el-transfer-panel pull-left transferHeader">选择门店</div>
          <div class="el-transfer-panel pull-right transferHeader">已选门店</div>
        </div>
        <el-transfer
          :props="{key: 'id', label: 'name'}"
          :titles="['全选', '全选']"
          :button-texts="['删除', '添加']"
          filterable
          v-model="check_store_list"
          :data="storeList"
        ></el-transfer>
        <span slot="footer" class="dialog-footer">
          <el-button size="small" type="primary" @click="saveStoreClick">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getList,
  getPage,
  get_check_store_list,
  addPackage,
  editPackage,
  delPackage,
  savePackage,
  getStoreList,
  getBrandList,
  saveStore,
  product,
  state,
} from "@/api/member/voucher_set";
import { money, num1to999999 } from "@/utils/validate";
import { pickerOptionsAfterF } from "@/utils";
export default {
  data() {
    const validateVal = (rule, value, callback) => {
      if (!money(value)) {
        callback(new Error("请输入正确的金额"));
      } else {
        callback();
      }
    };
    const num1to999999Vali = (rule, value, callback) => {
      if (!num1to999999(value)) {
        callback(new Error("请输入1-999999张数"));
      } else {
        callback();
      }
    };
    return {
      is_edit: false,
      storeDialog: false,
      list: null,
      listLoading: false,
      addEditDialog: false,
      related_list: [
        { id: "1", name: "关联快盈 " },
        { id: "2", name: "关联口碑" },
      ],
      type_list: [
        { id: "0", name: "未关联卡券代金券" },
        { id: "1", name: "关联卡券代金券" },
      ],
      recharge_list: [
        { id: "1", name: "临时卡" },
        { id: "2", name: "普通会员卡" },
        { id: "3", name: "精英会员卡" },
      ],
      pay_renewal_list: [
        { id: "1", name: "临时卡" },
        { id: "2", name: "普通会员卡" },
        { id: "3", name: "精英会员卡" },
        { id: "4", name: "10次卡" },
        { id: "5", name: "20次卡" },
        { id: "8", name: "星星卡" },
        { id: "9", name: "6次卡" },
        { id: "10", name: "12次卡" },
      ],
      pay_card_list: [
        { id: "1", name: "临时卡" },
        { id: "2", name: "普通会员卡" },
        { id: "3", name: "精英会员卡" },
        { id: "4", name: "10次卡" },
        { id: "5", name: "20次卡" },
        { id: "6", name: "季卡" },
        { id: "7", name: "年卡" },
        { id: "8", name: "星星卡" },
        { id: "9", name: "6次卡" },
        { id: "10", name: "12次卡" },
      ],
      storeList: null,
      brandList: null,
      check_store_list: [],
      product_info: {},
      url: "",
      totalDataNumber: 1,
      formInline: {
        is_related: "0",
        name: "",
        brand_id: "",
      },
      saveStore: {
        id: "",
        store_list: [],
      },
      saveForm: {
        brand_id: "",
        pickerDate: [],
        name: "",
        limit_money: "",
        discount_money: "",
        threshold: "",
        number: 1,
        remark: "",
        product_id: "",
        is_related: false,
        is_recharge: false,
        is_pay_card: false,
        is_pay_renewal: false,
        is_ticket: "0",
        recharge_id: [],
        pay_card_id: [],
        pay_renewal_id: [],
        is_re: false,
        is_collect: "",
      },
      rules: {
        product_id: [
          { required: true, message: "请输入商品ID", trigger: "blur" },
        ],
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        pickerDate: [
          { required: true, message: "请选择时间", trigger: "blur" },
        ],
        limit_money: [
          { required: true, validator: validateVal, trigger: "blur" },
        ],
        discount_money: [
          { required: true, validator: validateVal, trigger: "blur" },
        ],
        threshold: [
          { required: true, validator: validateVal, trigger: "blur" },
        ],
        number: [
          { required: true, validator: num1to999999Vali, trigger: "blur" },
        ],
      },
      pickerOptions: pickerOptionsAfterF(),
    };
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      //当进入组件之前，执行 beforRouteEnter 路由钩子函数 ,//参数vm就是当前组件的实例。
      if (!vm.brandList) {
        vm.getBrand();
      }
    });
  },
  methods: {
    getProduct(id) {
      this.product_info = {};
      product({ product_id: id }).then((response) => {
        this.product_info = response;
      });
    },
    applyChange(type) {
      switch (type) {
        case 1:
          if (!this.saveForm.is_recharge) {
            this.saveForm.recharge_id = [];
          }
          break;
        case 2:
          if (!this.saveForm.is_pay_renewal) {
            this.saveForm.pay_renewal_id = [];
          }
          break;
        case 3:
          if (!this.saveForm.is_pay_card) {
            this.saveForm.pay_card_id = [];
          }
          break;
        default:
          break;
      }
    },
    relatedChange() {
      this.saveForm.product_id = "";
    },
    deployStoreClick(id) {
      get_check_store_list({ id: id }).then((response) => {
        this.check_store_list = response;
      });
      this.saveStore.id = id;
      this.storeDialog = true;
    },
    saveStoreClick() {
      this.saveStore.store_list = this.check_store_list;
      saveStore(this.saveStore).then((response) => {
        this.$message({
          type: response.code == 1 ? "success" : "error",
          message: response.message,
        });
        this.storeDialog = false;
      });
    },
    delClick(index) {
      if (this.saveForm.rules.length == 1) {
        this.saveForm.rules[index].limit_money = "";
        this.saveForm.rules[index].give = "";
      } else {
        this.saveForm.rules.splice(index, 1);
      }
    },
    getBrand() {
      getBrandList({ org: 1, category_id: 340 }).then((response) => {
        this.brandList = response;
        this.formInline.brand_id = response[0].id;
        this.brandChange();
        if (this.list == null) {
          this.fetchData();
        }
      });
    },
    brandChange() {
      this.fetchData();
      this.getStore();
    },
    getStore() {
      getStoreList({ brand: this.formInline.brand_id, category_id: 340 }).then(
        (response) => {
          this.storeList = response;
        }
      );
    },
    stateClick(id, index, is_enable) {
      let text =
        is_enable == "1"
          ? "启用后代金券将立即生效"
          : "停用后该代金券将会失效，相应配置门店将无法使用该代金券";
      this.$confirm(text, "提示", { type: "warning" }).then(() => {
        state({ id: id, is_enable: is_enable }).then((response) => {
          this.$message({
            type: response.code == 1 ? "success" : "error",
            message: response.message,
          });
          if (response.code == 1) {
            this.list[index].is_enable = is_enable == 1 ? 1 : 0;
          }
        });
      });
    },
    addEditClick(row) {
      this.saveForm.pickerDate = row ? [row.effect_time, row.stop_time] : [];
      this.saveForm.product_id = row ? row.product_id : "";
      this.saveForm.name = row ? row.name : "";
      this.saveForm.limit_money = row ? row.limit_money : "";
      this.saveForm.discount_money = row ? row.discount_money : "";
      this.saveForm.threshold = row ? row.threshold : "";
      this.saveForm.number = row ? row.number : 1;
      this.saveForm.remark = row ? row.remark : "";
      this.saveForm.is_related = row ? row.is_related : "0";
      this.saveForm.is_collect = row ? row.is_collect + "" : "";

      this.saveForm.is_ticket = row ? row.is_ticket + "" : "0";
      this.saveForm.recharge_id = row
        ? row.recharge_id.length > 0
          ? row.recharge_id.split(",")
          : []
        : [];
      this.saveForm.pay_renewal_id = row
        ? row.pay_renewal_id.length > 0
          ? row.pay_renewal_id.split(",")
          : []
        : [];
      this.saveForm.pay_card_id = row
        ? row.pay_card_id.length > 0
          ? row.pay_card_id.split(",")
          : []
        : [];
      this.saveForm.is_recharge =
        this.saveForm.recharge_id.length > 0 ? true : false;
      this.saveForm.is_pay_renewal =
        this.saveForm.pay_renewal_id.length > 0 ? true : false;
      this.saveForm.is_pay_card =
        this.saveForm.pay_card_id.length > 0 ? true : false;

      this.is_edit = row ? true : false;

      this.saveForm.is_re = row && row.is_collect > 0 ? true : false;

      this.addEditDialog = true;
    },
    savePackageClick(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (
            this.saveForm.recharge_id.length == 0 &&
            this.saveForm.pay_renewal_id.length == 0 &&
            this.saveForm.pay_card_id.length == 0 &&
            this.saveForm.is_ticket == "0"
          ) {
            this.$message({ type: "error", message: "适用业务必须填写一个" });
            return;
          }
          this.saveForm.brand_id = this.formInline.brand_id;
          this.saveForm.effect_time = this.saveForm.pickerDate[0];
          this.saveForm.stop_time = this.saveForm.pickerDate[1];
          let data = JSON.parse(JSON.stringify(this.saveForm));
          savePackage(data, this.url).then((response) => {
            this.addEditDialog = false;
            this.$message({
              type: response.code == 1 ? "success" : "error",
              message: response.message,
            });
            this.fetchData();
          });
        }
      });
    },
    delPackageClick(id, index) {
      this.$confirm("是否确认删除，删除后代金券不可恢复", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        delPackage({ id: id }).then((response) => {
          this.$message({
            type: response.code == 1 ? "success" : "error",
            message: response.message,
          });
          if (response.code == 1) {
            this.list.splice(index, 1);
          }
        });
      });
    },
    callOf(formName) {
      this.$refs[formName].resetFields();
    },
    // 搜索
    searchClick() {
      this.fetchData();
    },
    // 列表获取
    fetchData() {
      this.listLoading = true;
      getList(this.formInline)
        .then((response) => {
          response.forEach((val, i) => {
            val.discount_money = (val.discount_money / 100).toFixed(2) * 1;
            val.limit_money = (val.limit_money / 100).toFixed(2) * 1;
            val.threshold = (val.threshold / 100).toFixed(2) * 1;
          });
          this.list = response;
          this.listLoading = false;
        })
        .catch((res) => {
          this.listLoading = false;
        });
    },
  },
  watch: {
    "saveForm.product_id": function (val) {
      this.saveForm.product_id = this.saveForm.product_id.replace(
        /^\s+|\s+$/g,
        ""
      );
    },
  },
};
</script>